"use client"
import React, { useEffect, useState } from 'react';
import './page.css';
import { request } from '@/lib/request';
import axios from 'axios';

const UserList = ({ users }) => {
  return (
    <div className="user-list-container">
      <h1>User List</h1>
      {users.map((user, index) => (
        <div className="user-card" key={index}>
          <h3>Username: {user.username}</h3>
          <p>Password: {user.password}</p>
        </div>
      ))}
    </div>
  );
};

const AddUserForm = ({ onAddUser }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleAddUser = () => {
    if (username.trim() && password.trim()) {
      onAddUser({ username, password });
      setUsername('');
      setPassword('');
    }
  };

  return (
    <div className="add-user-form">
      <input type="text" placeholder="Enter username" value={username} onChange={(e) => setUsername(e.target.value)} />
      <input type="password" placeholder="Enter password" value={password} onChange={(e) => setPassword(e.target.value)} />
      <button onClick={handleAddUser}>Add User</button>
    </div>
  );
};


// 主页面---------------------------------
export default function Home() {
const getUertList = async () => {
  const userList = await request.get('/api/user')
  console.log(userList.data.data);
  setUsers(userList.data.data)
}

  const [users, setUsers] = useState([]);

  useEffect(()=> {
    getUertList()
  },[])

  const addUser = async (newUser) => {
    // const {username,password} = newUser
    // const formData = new FormData();
    // formData.append('username', username);
    // formData.append('password', password);
    const response = await request.post('/api/user', newUser);
    console.log(response);
    setUsers([...users, newUser]);
  };

  return (
    <div>
      <AddUserForm onAddUser={addUser} />
      <UserList users={users} />
    </div>
  );
}
